from SeleniumDemo.auth_proxy import co
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from lxml import etree
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
import time
from selenium.webdriver.common.action_chains import ActionChains
import csv
from fake_useragent import UserAgent
from PIL import Image  # 用于打开图片和对图片处理
from aip import AipOcr
import pandas as pd


# 初始化
def init_driver(url):
    # 未在PATH环境变量中设置，需要设置驱动可执行路径
    driver = webdriver.Chrome(executable_path='D:\\webdriver\\chromedriver.exe', chrome_options=co)
    driver.maximize_window()  # 窗口最大化
    driver.get(url)
    return driver


# 获取页面url
def get_url(drive, search, save_path):
    # 初始化查询条件
    init_search(search)
    flag = "否"
    # 判断是否有验证码，如果验证码延时40秒
    img_count = 548
    while True:
        try:
            img_element = driver.find_element_by_xpath('//img[@id="ipocaptcha_CaptchaImage"]')

            time.sleep(2)
            # 初始化查询条件
            # init_search(search)
        except:
            try:
                # 未搜索到结果
                WebDriverWait(driver, 2).until(
                    EC.presence_of_element_located((By.CLASS_NAME, "error-summary-list")))
                # 保存结果
                with open(save_path, 'a+', encoding="utf-8-sig", newline='') as f:
                    csv_writer = csv.writer(f)
                    csv_writer.writerow([search, flag])
                return
            except:
                # 搜索到结果
                WebDriverWait(driver, 2).until(
                    EC.presence_of_element_located((By.CLASS_NAME, "search-results")))
                selector = etree.HTML(driver.page_source)
                for s in selector.xpath('//div[@class="search-results"]/div[@class="grid-row"]/div[@class="column-two-thirds"]'):
                    title = "".join(s.xpath('./p[@class="bold-medium"]/a//text()'))
                    if title.find("EU") == 0 or title.find("WE") == 0 or title.find("WO") == 0:
                        flag = "是"
                    # 保存结果
                    with open(save_path, 'a+', encoding="utf-8-sig", newline='') as f:
                        csv_writer = csv.writer(f)
                        csv_writer.writerow([search, flag])
                    driver.find_element_by_xpath('//a[contains(text(),"New search")]').click()
                    return
                try:
                    driver.find_element_by_xpath('//a[contains(@title,"Go to next page")]').click()
                except:
                    driver.find_element_by_xpath('//a[contains(text(),"New search")]').click()
                    return
                # 保存结果
                with open(save_path, 'a+', encoding="utf-8-sig", newline='') as f:
                    csv_writer = csv.writer(f)
                    csv_writer.writerow([search, flag])

def init_search(search):
    # 设置等待
    WebDriverWait(driver, 50).until(
        EC.presence_of_element_located((By.NAME, "wordSearchPhrase")))
    # 清空search
    driver.find_element_by_name("wordSearchPhrase").clear()
    # 设置搜索条件
    driver.find_element_by_name("wordSearchPhrase").send_keys(search)

    selectTag = Select(driver.find_element_by_name("wordSearchType"))
    selectTag.select_by_index(1)
    time.sleep(0.2)
    selectTag1 = Select(driver.find_element_by_name("legalStatus"))
    selectTag1.select_by_index(1)
    # time.sleep(0.2)
    # selectTag2 = Select(driver.find_element_by_name("pageSize"))
    # selectTag2.select_by_index(4)
    # 查询
    driver.find_element_by_id("button").click()


def close_driver(driver):
    driver.quit()


if __name__ == '__main__':
    search_list = []
    # line_num = 0
    # with open("./XDY_result.csv", 'r', encoding="utf-8-sig", newline='') as f:
    #     reader = csv.reader(f)
    #     for line in reader:
    #         search_list.append(line[0].strip())
    source_path = "./X/CW.xlsx"
    save_path = "./X/CW_result1.csv"
    line_num = 1
    df = pd.read_excel(source_path)
    for index, row in df.iterrows():
        search_list.append(row[0].strip())

    url = "http://trademarks.ipo.gov.uk/ipo-tmtext?reset"
    driver = init_driver(url)

    for s in search_list:
        line_num += 1
        print(f"====count：{len(search_list) - line_num}=======line：{line_num}=====search：{s}=============")
        get_url(driver, s, save_path)

